package org.tacademy.basic.calendar;

import java.util.ArrayList;
import java.util.StringTokenizer;

import org.tacademy.basic.calendar.databasemanager.DBConstant;
import org.tacademy.basic.calendar.databasemanager.DBManager;
import org.tacademy.basic.calendar.databasemanager.DBRequest;
import org.tacademy.basic.calendar.databasemanager.MyDatabaseOpenHelper;
import org.tacademy.basic.calendar.databasemanager.ScheduleRequest;

import android.app.Fragment;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class ListFragment extends Fragment {

	ListView listview;
	
	MyDatabaseOpenHelper mDBHelper;
	
	SimpleCursorAdapter mAdapter;
	Cursor mCursor = null;
	
	Handler mHandler = new Handler();
	
	ArrayList<ItemData> result=null;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		
		View v = inflater.inflate(R.layout.list_schedule, null);
		mDBHelper = new MyDatabaseOpenHelper(MyApplication.getContext(), null, null, 0);
		
		listview = (ListView) v.findViewById(R.id.showlistview);
		
		String[] from = { DBConstant.ScheduleTable.DATE, DBConstant.ScheduleTable.TITLE };
		int[] to = { R.id.simpleDate, R.id.simpleTitle };
		
		mAdapter = new SimpleCursorAdapter(MyApplication.getContext(), R.layout.simple_list_layout, null, from, to, 0);
		listview.setAdapter(mAdapter);
		
		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View arg1, int position,
					long arg3) {
				// TODO Auto-generated method stub

				Cursor c = (Cursor)mAdapter.getItem(position);
				InfoSchedule info = new InfoSchedule(c);
				info.show(getFragmentManager(), "info_dialog");
			}
		});
		
	    return v;
	}
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		
		ScheduleRequest request = new ScheduleRequest();

		DBManager.getInstance().getAsyncDBProcess(request, new DBRequest.OnQueryCompleteListener() {
			
			@Override
			public void onQueryCompleted(DBRequest request) {
				// TODO Auto-generated method stub
				
				Cursor c = (Cursor)request.getResult();
				
				if (mCursor != null) {
					mCursor.close();
					mCursor = null;
				}
				
				mCursor = c;
				
				mAdapter.swapCursor(mCursor);
			}
		}, mHandler);
		
		super.onResume();
	}

}
